extension :production_checking => :http_check do
  require "net/http"
  require "uri"

  task :check_production do
    execute_previous if previous_defined?

    url_to_check = fetch(:http_check_url, nil) || production_url
    url_to_check = "http://#{url_to_check}" unless url_to_check =~ /^http/
    logger.info "checking url: #{url_to_check}"
    
    check_url = lambda do |redirection_counter|
      raise "too many redirects" if redirection_counter == 0
      
      uri = URI.parse url_to_check
      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = (uri.scheme == 'https')
      begin
        response =  http.get(uri.path.length > 0 ? uri.path : "/")
      rescue e => TimeoutError
        raise "timeout occured while sending http request"
      end

      case response
      when Net::HTTPSuccess
        if exists? :http_check_expected_title
          raise "can't find the title in response" unless response.body =~ %r{<TITLE>(.*?)</TITLE>}im
          title = $1
          raise "unexpected title value: #{title}" if title.strip != fetch(:http_check_expected_title).strip
        end
        if exists? :http_check_regexp
          raise "response body doesn't match given expression" unless response.body =~ fetch(:http_check_regexp)
        end
      when Net::HTTPRedirection
        url_to_check = response['location']
        logger.info "redirected to: #{url_to_check}"
        check_url.call(redirection_counter - 1)
      else
        response.error!
      end
    end
    
    check_url.call 10
  end
  
end
